import axios from 'axios'
import Vue from 'vue'
import state from '@/store/state'
import { MessageBox } from 'element-ui'
import qs from 'qs'
axios.defaults.timeout = ""
axios.defaults.baseURL = ''


//http request  拦截器
axios.interceptors.request.use(
  config => {
    const param = {
      "token":state.userInfo.pushToken?state.userInfo.pushToken:"111",
      "phone":state.userInfo.phoneNum?state.userInfo.phoneNum:"11",
      "deviceId":"7b9ea65e59c81aa4",
      "osversion":"1.0.0",
      "requestId":"PC",
      "appName":1,
      "market":"rechage",
      "source":5,
      "mode":"debug",
      "createTime":"0212345648796",
      "appversion":"develop"
    }
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',
      'auth': JSON.stringify(param)
    }
    return config;
    
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.errCode == 500){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    return response;
  },
  error => {
    // setTimeout(function(){
    //   Vue.$alert('网络忙，请稍后再试!','富易')
    // },2000) 
    return Promise.reject(error)
  }
)

export default function ajax(url = '', params = {}, type = 'GET') {
     // 1. 定义promise对象
     let promise;
     return new Promise((resolve, reject)=>{
        // 2. 判断请求的方式
        if('GET' === type){
              // 2.1 拼接请求字符串
              if(params !== ""){
                let paramsStr = '';
                Object.keys(params).forEach(key =>{
                   paramsStr += key + '=' + params[key] + '&'
                });
                // 2.2 过滤最后的&
                if(paramsStr !== ''){
                   paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'))
                }
                // 2.3 完整路径
                url += '?' + paramsStr;
              }                        
              // 2.4 发送get请求
              promise = axios.get(url)
        }else if('POST' === type){   
              params = qs.stringify(params);   
              promise = axios.post(url, params)
        }
        // 3. 返回请求的结果
        promise.then((response)=>{     
          resolve(response.data);
        }).catch((error) => {
          console.log(error);
            reject(error)
        })
     })
    
}


 